package com.situ.day8;

import org.junit.Test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ExceptionDemo {

    @Test
    public void test1() {
        //运行时异常是程序员自己写的代码有问题
        //java.lang.ArithmeticException: / by zero
        //int num = 1 / 0;

        String str = null;
        System.out.println(str.toUpperCase());

        //编译时异常：未雨绸缪
        //Unhandled exception: java.io.FileNotFoundException
        try {
            FileInputStream fileInputStream = new FileInputStream("b.txt");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        System.out.println("ExceptionDemo.test1");

    }

    @Test
    public void test2() {
        try {
            // 需要检查的代码（可能会抛出异常，也可能不会抛出异常）
            FileInputStream fileInputStream = new FileInputStream("a.txt");
            System.out.println("ExceptionDemo.test2 try");
        } catch (FileNotFoundException e) {
            //捕获异常后要处理异常
            e.printStackTrace();
        } finally {
            //一定会被执行的代码（不管异常抛不抛出都会执行）
            System.out.println("finally");
        }
        System.out.println("ExceptionDemo.test2");
    }

    @Test
    public void test3() {
        //JDBC加载mysql驱动
        //java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void test55()  {
        try {
            show();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //抛出编译时异常，谁调用我谁去处理
    public void show() throws ClassNotFoundException {
        Class.forName("com.mysql.jdbc.Driver");
    }

    @Test
    public void test554() {
        try {
            FileInputStream fileInputStream = new FileInputStream("a.txt");
            //Unhandled exception: java.io.IOException
            fileInputStream.read();
            //Exception 'java.io.FileNotFoundException' has already been caught
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }  catch (IOException e) {
            e.printStackTrace();
        }
    }
}
